package com.chen.websocket;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.chen.pojo.bean.WsResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import java.util.Objects;

import static com.chen.websocket.WSClient.startWS;


@ClientEndpoint
@Slf4j
@Component
public class WSHandler {


    @OnOpen
    public void onOpen(Session session) {
        WSClient.session = session;
    }

    @OnMessage
    public void processMessage(String message) {
        log.info("websocketRecive接收推送消息" + message);
        try {
            WsResult wsResult = JSONObject.parseObject(message, WsResult.class);
            if ("success".equals(wsResult.getCode())) {
                String result2 = HttpRequest.post("http://127.0.0.1:8083/alipay/callback")
                        .body(wsResult.getResultObj())
                        .execute().body();
                if (Integer.parseInt(result2) > 0) {
                    log.info("[processMessage] pay success.");
                }
            } else {
                log.info("[processMessage] pay fail.");
            }
        } catch (Exception e) {
            log.error("[processMessage] handler json data may be error. error = {}.", e.getMessage());
        }
    }

    @OnError
    public void processError(Throwable t) {
        WSClient.session = null;
        try {
            Thread.sleep(5000);
            startWS();
        } catch (InterruptedException e) {
            log.error("---websocket processError InterruptedException---", e);
        }
        log.error("---websocket processError error---", t);
    }

    @OnClose
    public void processClose(Session session, CloseReason closeReason) {
        log.error(session.getId() + closeReason.toString());
    }

    public void send(String sessionId, String message) {
        try {
            log.info("send Msg:" + message);
            if (Objects.nonNull(WSClient.session)) {
                WSClient.session.getBasicRemote().sendText(message);
            } else {
                log.info("---websocket error----");
            }

        } catch (Exception e) {
            log.error("---websocket send error---", e);
        }

    }
}
